<!-- components/TabNav.vue -->
<template>
  <div class="tab-nav-container">
    <div class="tags-view-container">
      <el-tag
        v-for="item in tabs"
        :key="item.name"
        :class="['tag-item', activeTab === item.name ? 'active' : '']"
        :closable="item.name !== '/dashboard'"
        @click="handleTabClick(item.name)"
        @close.stop="removeTab(item.name)"
      >
        <div class="tab-label">
          <span v-if="item.name === activeTab" class="active-indicator"></span>
          <span>{{ item.label }}</span>
        </div>
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useLayoutStore } from '@/stores/layout';
import { useRoute, useRouter } from 'vue-router';

const layoutStore = useLayoutStore();
const router = useRouter();
const route = useRoute();

const activeTab = ref(layoutStore.getActiveMenu || '/dashboard');
const tabs = ref([
  { name: '/dashboard', label: '首页' }
]);

const handleTabClick = (name) => {
  activeTab.value = name;
};

const removeTab = (targetName) => {
  if (activeTab.value === targetName) {
    tabs.value.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs.value[index + 1] || tabs.value[index - 1];
        if (nextTab) {
          activeTab.value = nextTab.name;
        }
      }
    });
  }
  
  tabs.value = tabs.value.filter(tab => tab.name !== targetName);
};

// 监听活动标签变化
watch(activeTab, (newVal) => {
  layoutStore.setActiveMenu(newVal);
  router.push(newVal);
});

// 监听路由变化
watch(() => route.path, (newPath) => {
  const isExist = tabs.value.some(tab => tab.name === newPath);
  if (!isExist) {
    tabs.value.push({ name: newPath, label: route.meta.title });
  }
  activeTab.value = newPath;
}, { immediate: true });
</script>

<style scoped>
.tab-nav-container {
  padding: 0;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.tags-view-container {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 10px;
  overflow-x: auto;
  white-space: nowrap;
}

.tags-view-container::-webkit-scrollbar {
  display: none;
}

.tag-item {
  height: 32px;
  line-height: 32px;
  margin-right: 5px;
  cursor: pointer;
  border: 1px solid #efefef;
  padding: 0 10px;
  background-color: #fff;
  color: #303133;
}

.tag-item.active {
  background-color: #409eff;
  color: #fff;
}

.tab-label {
  display: flex;
  align-items: center;
}

.active-indicator {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #fff;
  margin-right: 6px;
}

/* 修改 el-tag 的关闭按钮样式 */
.tag-item :deep(.el-tag__close) {
  color: inherit;
  font-weight: bold;
}

.tag-item.active :deep(.el-tag__close) {
  color: #fff;
  background-color: transparent;
}

.tag-item.active :deep(.el-tag__close:hover) {
  background-color: rgba(255, 255, 255, 0.2);
}

.tag-item:not(.active) :deep(.el-tag__close:hover) {
  background-color: #ddd;
  color: #333;
}
</style>